import { Component, OnInit } from '@angular/core';
import { MyModalHelper } from '@core/my-modal.helper';
import { NzMessageService } from 'ng-zorro-antd';
import { GoodsService } from '@core/routes-services/goods.service';
import { Router } from '@angular/router';
import { GoodsClassService } from '@core/routes-services/goods-class.service';
import { YESNO_OPTION } from '../../../constant/dictionary';

@Component({
  selector: 'app-goods-list',
  templateUrl: './goods-list.component.html',
})
export class GoodsListComponent implements OnInit {

  isLoading = false;
  keyword: any;
  classId: any;
  status: any;
  allowRetail: any;
  page: any = { number: 1, size: 10, totalElements: 0, content: [] };

  yesOrNo: any [] = YESNO_OPTION;
  goodsClassOptions: any [] = [];

  constructor(private message: NzMessageService,
              private router: Router,
              private goodsService: GoodsService,
              private goodsClassService: GoodsClassService,
              private modalHelper: MyModalHelper) {
  }

  ngOnInit() {
    this.initClassOptions();
    this.initPage();
  }

  initClassOptions() {
    this.goodsClassService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.goodsClassOptions = res.data.goodsClassList;
      } else {
        this.message.warning(res.message);
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
    });
  }

  initPage() {
    this.isLoading = true;
    this.goodsService.pagination(this.page, this.keyword, this.classId,this.status,this.allowRetail).then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.page = res.data;
        ++this.page.number;
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      this.isLoading = false;
    });
  }

  /**
   * 搜索重置分页数据
   */
  search() {
    this.page = { number: 0, size: 10, totalElements: 0, content: [] };
    this.initPage();
  }

  changePageNo(pageNo) {
    this.page = { number: pageNo, size: 10, totalElements: 0, content: [] };
    this.initPage();
  }

  addEntity = () => {
    this.router.navigate(['/goods/list/add'], { queryParams: { id: 0 } });
  };

  updateStatus = (data) => {
    this.goodsService.updateStatus(data.id, { status: data.status == 1 ? 2 : 1 }).then((data) => {
      this.changePageNo(this.page.number);
      this.message.success('修改成功');
    }, error => console.log('修改出错，后续处理'));
  };

}
